package com.cxmx.escort.controller;

import com.cxmx.escort.common.alioss.UploadOss;
import com.cxmx.escort.common.annotation.RequestJson;
import com.cxmx.escort.common.utils.result.OutDataUtil;
import com.cxmx.escort.config.mp.WxMpConfiguration;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Edward
 */
@AllArgsConstructor
@RestController
@RequestMapping("/wx/redirect")
public class WxRedirectController {
    private final WxMpService wxService;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @GetMapping("/greet/{code}")
    public String greetUser(@PathVariable("code") String code) {
        if (!this.wxService.switchover("wxe44143f0f73fa931")) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", "wx1c34a5f48214030f"));
        }

        try {
            WxMpOAuth2AccessToken accessToken = wxService.oauth2getAccessToken(code);
//            WxMpUser user = wxService.oauth2getUserInfo(accessToken, null);
            return accessToken.getOpenId();
        } catch (WxErrorException e) {
            this.logger.error(e.getMessage(), e);
            return e.toString();
        }
    }

    @PostMapping("/jssdk")
    public WxJsapiSignature getsdk(@RequestJson("url") String url) {
        if (!this.wxService.switchover("wxe44143f0f73fa931")) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", "wx1c34a5f48214030f"));
        }
        WxMpService mpService = WxMpConfiguration.getMpServices().get("wx1c34a5f48214030f");
        try {
            WxJsapiSignature accessToken = mpService.createJsapiSignature(URLDecoder.decode(url, "utf-8"));
            return accessToken;
        } catch (WxErrorException e) {
            this.logger.error(e.getMessage(), e);
            return null;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    @PostMapping(value = "/filesUpload/{id}")
    public void filesUpload(@PathVariable("id") String id, HttpServletResponse response) {
        List<Map<String, String>> fileUrlList = new ArrayList<>();
        try {
            // 获得一个在系统临时目录的文件
//            WxMpService mpService = WxMpConfiguration.getMpServices().get("wx1c34a5f48214030f");
            File file = wxService.getMaterialService().mediaDownload(id);
            logger.info(file.getName() + "name" + file.getPath());
            MultipartFile mulFile = new MockMultipartFile(
                    "haha.jpg",        //文件名
                    "haha.jpg",        //originalName 相当于上传文件在客户机上的文件名
                    ContentType.APPLICATION_OCTET_STREAM.toString(),    //文件类型
                    new FileInputStream(file)                           //文件流
            );

            logger.info("go there");
            Map<String, String> mapFlie = new HashMap<>();
            InputStream stream = mulFile.getInputStream();
            Long size1 = mulFile.getSize();
            String fileName = mulFile.getOriginalFilename();
            String fileNameOSS = UploadOss.uploadFile(fileName, stream, size1);
            String fileUrls = UploadOss.GET_ALI_BUCK_URL + "/" + UploadOss.fileName + fileNameOSS;
            mapFlie.put("fileName", fileName);
            mapFlie.put("fileUrl", fileUrls);
            fileUrlList.add(mapFlie);

            OutDataUtil.writeSuccessJSON(response, "上传成功", fileUrlList);
        } catch (
                Exception e) {
            e.getStackTrace();
            OutDataUtil.writeFailJSON(response, "上传失败", e.getStackTrace());
        }
    }
}
